//
//  LoginVC.swift
//  ProjectApp
//
//  Created by jack on 2021/1/11.
//

import UIKit

class LoginVC: BaseVC {
    @IBOutlet weak var accountTxtField: UITextField!
    @IBOutlet weak var passwordTxtField: UITextField!
    @IBOutlet weak var loginBtn: UIButton!
    @IBOutlet weak var msgLbl: UILabel!
    
    var vm: LoginVM?
    let msgObservable: PublishSubject<String> =  PublishSubject<String>()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "登录"

        // 传入账号、密码、登录按钮的事件监听
        self.vm = LoginVM(input: (account: accountTxtField.rx.text.orEmpty.asObservable(), password: passwordTxtField.rx.text.orEmpty.asObservable(), loginTap: loginBtn.rx.tap.asObservable()))
        
        // 登录按钮订阅ViewModel的signupEnabled属性，实时监听输入的账号、密码是否符合要求来判断登录按钮能否点击
        self.vm?.signupEnabled.subscribe(onNext: { [weak self](valid) in
            guard let self = self else { return }
            self.loginBtn.isEnabled = valid
            self.loginBtn.alpha = valid ? 1.0 : 0.5
        }, onError: { (error) in
            
        }, onCompleted: {
            
        }, onDisposed: {
            
        }).disposed(by: disposeBag)
        
        // 订阅ViewModel的loginResult属性，实时监听登录结果
        self.vm?.loginResult.subscribe(onNext: { [weak self](suc, errorMsg) in
            guard let self = self else { return }
            if suc { // 登录成功
                DPrint(message: "登录成功")
                self.msgObservable.onNext("登录成功")
            } else {// 账号/密码错误
                DPrint(message: "登录失败")
                self.msgObservable.onNext(errorMsg)
            }
        }, onError: { (e: Error) in
            // 网络出错、接口返回数据模型不对等异常情况回调
            DPrint(message: "登录失败:\(e.localizedDescription)")
        }, onCompleted: {
            
        }, onDisposed: {
            
        }).disposed(by: disposeBag)
        
        // 消息提示UILabel绑定
        self.msgObservable.bind(to: self.msgLbl.rx.text).disposed(by: disposeBag)
    }
}
